#include "ThreadPoolObject.h"
#include "ThreadSafePrinter.h"

HTHREADPOOL_NAMESPACE_BEGIN

    ThreadPoolObject::ThreadPoolObject(ThreadType type, AtomicQueue<Task> * poolTaskQueue)
    : ThreadObject(type)
    , m_poolTaskQueue(poolTaskQueue)
    {
        m_isBatchExecution.store(false);
    }

    ThreadPoolObject::~ThreadPoolObject() {}

    void ThreadPoolObject::runTask(Task & task)
    {
        // TODO
        m_state = ThreadState::kRunning;
        task();
        m_excuteTotalTaskNum++;
        m_state = ThreadState::kWaiting;
    }

    void ThreadPoolObject::runTasks(TaskArr & tasks)
    {
        m_state = ThreadState::kRunning;
        for(auto& task : tasks) {
            task();
        }

        m_excuteTotalTaskNum += tasks.size();
        m_state = ThreadState::kWaiting;
    }

    unsigned long long ThreadPoolObject::getExcuteTasks() { return m_excuteTotalTaskNum; }

    bool ThreadPoolObject::popPoolTask(TaskArrRef tasks)
    {
        bool result = m_poolTaskQueue->tryPop(tasks, 5);
        if(!result && ThreadType::kIdle == m_type) {
            result = m_poolTaskQueue->tryPop(tasks, 1);
        }
        return result;
    }

    bool ThreadPoolObject::popPoolTask(TaskRef task)
    {
        bool result = m_poolTaskQueue->tryPop(task);
        if(!result && ThreadType::kIdle == m_type) {
            //            result = m_poolTaskQueue->tryPop(task);
        }
        return result;
    }

HTHREADPOOL_NAMESPACE_END
